package com.qwq.service.impl;

import com.qwq.dto.SendRoomMessageInputDto;
import com.qwq.dto.lcu.*;
import com.qwq.infrastructure.exception.StringResponseException;
import com.qwq.model.LcuApiInfo;
import com.qwq.service.LcuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.List;
import java.util.TimeZone;

/*
 * 封装lcuApi接口
 * */
@Service
public class LcuServiceImpl implements LcuService {
    private static String _baseUrl;
    private final RestTemplate _restTemplate;
    private final LcuApiInfo _lcuApiInfo;

    @Autowired
    public LcuServiceImpl(RestTemplate restTemplate, LcuApiInfo lcuApiInfo) {
        _restTemplate = restTemplate;
        _lcuApiInfo = lcuApiInfo;
        _baseUrl = "https://127.0.0.1:" + lcuApiInfo.getPort() + "/";
    }

    /*
     *选英雄时获取房间信息
     * */
    public LolChampSelectV1SessionResponse getRoomInfo() {
        String requestUrl = _baseUrl + "lol-champ-select/v1/session";
        return _restTemplate.exchange(requestUrl, HttpMethod.GET, new HttpEntity<>(null, getLcuRequestHeaders()), LolChampSelectV1SessionResponse.class).getBody();
    }

    /**
     * 根据房间名称查询聊天信息
     *
     * @param roomName 房间id
     */
    public List<LolChatConversationsRoomNameMessageResponse> getMessagesByRoomName(String roomName) {
        String requestUrl = _baseUrl + "lol-chat/v1/conversations/" + roomName + "/messages";
        ParameterizedTypeReference<List<LolChatConversationsRoomNameMessageResponse>> typeReference = new ParameterizedTypeReference<>() {
        };
        return _restTemplate.exchange(requestUrl, HttpMethod.GET, new HttpEntity<>(null, getLcuRequestHeaders()), typeReference).getBody();
    }

    /**
     * 查询召唤师信息
     *
     * @param summonerId 召唤师id
     */
    public LolSummonerInfoResponse getSummonerInfo(String summonerId) {
        if (!StringUtils.hasText(summonerId)) {
            throw new StringResponseException("参数错误");
        }
        String requestUrl = _baseUrl + "lol-summoner/v1/summoners/" + summonerId;
        return _restTemplate.exchange(requestUrl, HttpMethod.GET, new HttpEntity<>(null, getLcuRequestHeaders()), LolSummonerInfoResponse.class).getBody();
    }

    /**
     * 查询战绩
     *
     * @param puuid      玩家唯一id
     * @param beginIndex 开始位置
     * @param endIndex   结束位置
     */
    public LolMatchHistoryResponse getMatchHistoryInfo(String puuid, int beginIndex, int endIndex) {
        String requestUrl = _baseUrl + "lol-match-history/v1/products/lol/" + puuid + "/matches?begIndex=" + beginIndex + "&endIndex=" + endIndex;
        return _restTemplate.exchange(requestUrl, HttpMethod.GET, new HttpEntity<>(null, getLcuRequestHeaders()), LolMatchHistoryResponse.class).getBody();
    }


    /**
     * 获取当前登陆用户信息
     */
    public LolSummonerInfoResponse getLoginSummonerInfo() {
        String requestUrl = _baseUrl + "lol-summoner/v1/current-summoner";
        return _restTemplate.exchange(requestUrl, HttpMethod.GET, new HttpEntity<>(null, getLcuRequestHeaders()), LolSummonerInfoResponse.class).getBody();
    }

    /**
     * 获取当前登陆大区
     *
     * @return ReportingEnvironmentOutputDto
     */
    public ReportingEnvironmentResponse getRiotclientV1CrashReportingEnvironment() {
        String requestUrl = _baseUrl + "riotclient/v1/crash-reporting/environment";
        RiotclientV1CrashReportingEnvironmentResponse response = _restTemplate.exchange(requestUrl, HttpMethod.GET, new HttpEntity<>(null, getLcuRequestHeaders()), RiotclientV1CrashReportingEnvironmentResponse.class).getBody();
        if (response == null) {
            throw new StringResponseException("获取当前登录大区接口响应为NULL");
        }
        return new ReportingEnvironmentResponse(response.getEnvironment());
    }

    /**
     * 获取头像
     *
     * @param id
     * @return 头像二进制数据
     */
    public byte[] getAvatarImg(String id) {
        String requestUrl = _baseUrl + "lol-game-data/assets/v1/profile-icons/" + id + ".jpg";
        return _restTemplate.exchange(requestUrl, HttpMethod.GET, new HttpEntity<>(getLcuRequestHeaders()), byte[].class).getBody();
    }

    /**
     * 获取当前登陆用户蓝色精粹
     */
    public LolBlueEssenceResponse getCurrentLolBlueEssenceResponse() {
        String requestUrl = _baseUrl + "lol-inventory/v1/wallet/lol_blue_essence";
        return _restTemplate.exchange(requestUrl, HttpMethod.GET, new HttpEntity<>(null, getLcuRequestHeaders()), LolBlueEssenceResponse.class).getBody();
    }

    /**
     * 获取英雄信息
     *
     * @param id 英雄id
     */
    public ChampionInfoResponse getChampionInfo(int id) {
        String requestUrl = _baseUrl + "lol-game-data/assets/v1/champions/" + id + ".json";
        return _restTemplate.exchange(requestUrl, HttpMethod.GET, new HttpEntity<>(null, getLcuRequestHeaders()), ChampionInfoResponse.class).getBody();
    }

    /**
     * 段位查询
     *
     * @param puuid 玩家唯一id
     * @return 段位信息
     */
    public LolRankedV1RankedStatsResponse getRankedInfo(String puuid) {
        String requestUrl = _baseUrl + "lol-ranked/v1/ranked-stats/" + puuid;
        return _restTemplate.exchange(requestUrl, HttpMethod.GET, new HttpEntity<>(null, getLcuRequestHeaders()), LolRankedV1RankedStatsResponse.class).getBody();
    }

    /**
     * 修改当前召唤师段位
     *
     * @param request 请求参数
     */
    @Override
    public void updateCurrentSummonerRankedInfo(LolUpdateRankedRequest request) {
        if (request.getLol() == null
                || !StringUtils.hasText(request.getLol().getRankedLeagueQueue())
                || !StringUtils.hasText(request.getLol().getRankedLeagueTier())) {
            throw new StringResponseException("段位类型和段位错误");
        }
        // 最强王者 宗师 大师 没有分级
        if (request.getLol().getRankedLeagueTier().equals("MASTER")
                || request.getLol().getRankedLeagueTier().equals("GRANDMASTER")
                || request.getLol().getRankedLeagueTier().equals("CHALLENGER")) {
            request.getLol().setRankedLeagueDivision(null);
        }
        String requestUrl = _baseUrl + "lol-chat/v1/me";
        LolUpdateRankedResponse response = _restTemplate.exchange(requestUrl, HttpMethod.PUT, new HttpEntity<>(request, getLcuRequestHeaders()), LolUpdateRankedResponse.class).getBody();
        if (response == null
                || !response.getLol().getRankedLeagueQueue().equalsIgnoreCase(request.getLol().getRankedLeagueQueue())
                || !response.getLol().getRankedLeagueTier().equalsIgnoreCase(request.getLol().getRankedLeagueTier())) {
            throw new StringResponseException("修改失败，请查看日志...");
        }
    }

    /**
     * 发送房间消息
     *
     * @param inputDto 发送消息入参
     * @return 是否成功
     */
    public boolean sendRoomMessage(SendRoomMessageInputDto inputDto) {
        if (!StringUtils.hasText(inputDto.getText()) || !StringUtils.hasText(inputDto.getRoomName()) || !StringUtils.hasText(inputDto.getSummonerId())) {
            throw new StringResponseException("SendRoomMessageInputDto参数错误");
        }
        String requestUrl = _baseUrl + "lol-chat/v1/conversations/" + inputDto.getRoomName() + "/messages";
        LolChatConversationMessageSendRequest requestData = new LolChatConversationMessageSendRequest();
        requestData.setType("chat");
        requestData.setFromId(inputDto.getSummonerId());
        requestData.setFromSummonerId(Long.parseLong(inputDto.getSummonerId()));
        requestData.setIsHistorical(false);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sss");
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        requestData.setTimestamp(simpleDateFormat.format(System.currentTimeMillis()) + "Z");
        requestData.setBody(inputDto.getText());
        LolChatConversationMessageSendResponse response = _restTemplate.postForObject(requestUrl, new HttpEntity<>(requestData, getLcuRequestHeaders()), LolChatConversationMessageSendResponse.class);
        if (response == null) {
            throw new StringResponseException("发送失败");
        }
        return StringUtils.hasText(response.getId());
    }

    /**
     * 根据名称获取召唤师信息
     *
     * @param name 召唤师名称
     * @return 召唤师信息
     */
    public LolSummonerInfoResponse getSummonerInfoByName(String name) {
        if (!StringUtils.hasText(name)) {
            throw new StringResponseException("参数错误");
        }
        String requestUrl = _baseUrl + "lol-summoner/v1/summoners?name=" + name;
        return _restTemplate.exchange(requestUrl, HttpMethod.GET, new HttpEntity<>(null, getLcuRequestHeaders()), LolSummonerInfoResponse.class).getBody();
    }

    /*
     * 获取授权请求头
     * */
    private HttpHeaders getLcuRequestHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", initAuthorization());
        headers.add("User-Agent", "LeagueOfLegendsClient");
        return headers;
    }

    /*
     *  初始化请求头授权参数
     * */
    private String initAuthorization() {
        String temp = "riot:" + _lcuApiInfo.getToken();
        byte[] encodeBytes = Base64.getEncoder().encode(temp.getBytes(StandardCharsets.UTF_8));
        return "Basic "+new String(encodeBytes);
    }

}
